package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Api(tags = "用户登录接口")
@Slf4j
public class LoginController {

    @Autowired
    private com.sky.service.UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 微信登录
     * @param code
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO  code) {
        log.info("微信用户登录：{}", code);
        System.out.println("code:"+code.getCode());
        User login = userService.login(code);
        //生成令牌;
        Map claims = new HashMap();
        claims.put(JwtClaimsConstant.USER_ID, login.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(login.getId())
                .openid(login.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
}
